import Paho from "paho-mqtt";
import { userStore } from "@/pinia/user";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";

const pinia = createPinia();
const _userStore = userStore(pinia);
const { profile } = storeToRefs(_userStore);

class MqttServer {
  constructor(topics = []) {
    this.host = profile.value.MqttIp
      ? profile.value.MqttIp
      : import.meta.env.VITE_APP_MQTT_HOST;
    this.port = Number(profile.value.MqttPort)
      ? Number(profile.value.MqttPort)
      : Number(import.meta.env.VITE_APP_MQTT_PORT);
    this.topics = topics;
    this.client = new Paho.Client(this.host, this.port, "qgj" + Date.now());
    this.qos = 0;
    this.events = {};
    this.keepAliveInterval = 60; // 保活时间，单位秒
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5; // 最大重连次数
    this.messageCallbacks = []; // 存储所有消息回调函数

    this.connect();
  }

  connect() {
    if (!this.host || !this.port) {
      ElMessage({
        type: "error",
        message: "未检测到MQTT服务配置，请联系管理员配置MQTT服务!",
        duration: 0,
        showClose: true,
      });
      throw new Error("未检测到MQTT服务配置，请联系管理员配置MQTT服务");
    }

    this.client.connect({
      keepAliveInterval: this.keepAliveInterval,
      onSuccess: () => {
        console.log(
          `\x1B[32m%s\x1B[0m`,
          `设备连接成功:${this.client.clientId}`
        );
        this.reconnectAttempts = 0; // 重置重连次数
        this.subscribeToTopics();
      },
      onFailure: (error) => {
        console.error("连接失败:", error);
        this.handleReconnect();
      },
    });

    // 设置消息接收回调
    this.client.onMessageArrived = (message) => {
      // 执行所有注册的回调函数
      this.messageCallbacks.forEach((callback) => {
        try {
          callback(message);
        } catch (error) {
          console.error("消息回调执行错误:", error);
        }
      });
    };

    // 设置连接断开回调
    this.client.onConnectionLost = (responseObject) => {
      console.log("连接断开:", responseObject);
      this.handleReconnect();
    };
  }

  // 添加消息回调方法
  addMessageCallback(callback) {
    if (
      typeof callback === "function" &&
      !this.messageCallbacks.includes(callback)
    ) {
      this.messageCallbacks.push(callback);
    }
  }

  // 移除消息回调方法
  removeMessageCallback(callback) {
    const index = this.messageCallbacks.indexOf(callback);
    if (index > -1) {
      this.messageCallbacks.splice(index, 1);
    }
  }

  subscribeToTopics() {
    for (let topic of this.topics) {
      this.client.subscribe(topic, { qos: this.qos });
    }
  }

  handleReconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      console.log(
        `尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`
      );
      setTimeout(() => {
        this.connect();
      }, 5000); // 5秒后重连
    } else {
      console.error("达到最大重连次数，连接失败");
    }
  }

  subscribe(topic) {
    console.log("订阅主题:", topic);
    this.client.subscribe(topic, { qos: this.qos });
  }

  publish(topic, message) {
    if (this.client.isConnected()) {
      this.client.send(topic, new Paho.Message(message));
    } else {
      console.error("MQTT客户端未连接，无法发送消息");
    }
  }

  disconnect() {
    console.log("断开连接");
    this.client.disconnect();
  }

  // 添加事件监听方法
  on(topic, callback) {
    this.events[topic] = callback;
  }
}

export default MqttServer;
